(function(D){
    var items = [],
        properties = [];

    var findPredicates = function(){
        var addProperties = function(indice, r){
            for(var i = 0 ; i < r.length ; i += 1){
		if(items[indice][r[i].pl.value]){
                    items[indice][r[i].pl.value].push(decodeURIComponent(r[i].ol.value));    
		}
		else{
                    items[indice][r[i].pl.value] = [decodeURIComponent(r[i].ol.value)];    
		}
                if(!(properties.hasElem(r[i].pl.value))){
                    properties.push( r[i].pl.value );
                }
            }
        };

        D.request("collections3.txt", {}, function(a){
                for (var i = 0; i < a.length; i += 1){
		    var href = "javascript:self.opener.DESANTI.openPage( \"" +
			a[i].page.value + "\" ); self.opener.focus( )";
        
                    items[i] = {
			"type":  a[i].type.value,
			"id":    a[i].c.value,
			"label": a[i].label.value,
			"thumb": a[i].thumb.value,
			"href": href
                    };
        
                    (function(){
                        var j = i;

                        if(a[i].type.value === "Collection Perso"){
                            D.request("collections.txt", {"collection": a[i].c.value}, 
				      function(results){
					  if(results.length > 0){
					      addProperties(j, results);
					  }
				      }, false, true);
                        }
                        else
                        {
                            D.request("collections2.txt", {"collection": a[i].c.value},
				      function(results){
					  if(results.length > 0){
					      addProperties(j, results); 
					  }
				      }, false, true);
                        }
                    })();
                }
            }, false, true);
    };

    window.onload = function(){
	findPredicates();
	
	DEBUG = {"items": items, "properties": properties};

	var facets = document.getElementById("facets");

	for(var i = 0; i < properties.length; i += 1){
	    var facet = document.createElement("div");
	    var expression = "." + properties[i];
    
	    facet.setAttribute("ex:role", "facet");
	    facet.setAttribute("ex:expression", expression);
	    facet.setAttribute("ex:facetLabel", decodeURIComponent(properties[i]));
            facets.appendChild(facet);
	}
	window.database = Exhibit.Database.create(); 
	var data = {"items": items};
	window.database.loadData(data); 
	window.exhibit = Exhibit.create(); 
	window.exhibit.configureFromDOM(); 
    }
})(DESANTI);
